package com.xunyji.springsecurity02.service;

import com.xunyji.springsecurity02.pojo.dataobject.SecurityAuthorityDO;
import com.xunyji.springsecurity02.pojo.dataobject.SecurityUserDO;
import com.xunyji.springsecurity02.pojo.dataobject.SecurityUserRoleDO;
import com.xunyji.springsecurity02.repository.AuthorityRepository;
import com.xunyji.springsecurity02.repository.UserRepository;
import com.xunyji.springsecurity02.repository.UserRoleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 王杨帅
 * @create 2018-09-08 20:46
 * @desc
 **/
@Service
public class UserService implements UserDetailsService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private UserRoleRepository userRoleRepository;

    @Autowired
    private AuthorityRepository authorityRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        // 根据用户名查找用户信息
        SecurityUserDO byUsername = userRepository.findByUsername(username);
        System.out.println(byUsername);

        // 根据用户ID查找用户角色关联信息
        List<SecurityUserRoleDO> byUserId = userRoleRepository.findByUserId(byUsername.getId());
        byUserId.stream().forEach(System.out::println);

        // 获取该用户对应的所有角色的ID列表
        List<Integer> collect = byUserId.stream()
                .map(info -> info.getRoleId())
                .collect(Collectors.toList());
        collect.stream().forEach(System.out::println);

        // 获取该用户对应的所有角色信息
        List<SecurityAuthorityDO> allById = authorityRepository.findAllById(collect);
        allById.stream().forEach(System.out::println);

        List<SimpleGrantedAuthority> authorityList = allById.stream()
                .map(info -> new SimpleGrantedAuthority(info.getAuthority()))
                .collect(Collectors.toList());
        authorityList.stream().forEach(System.out::println);

        // 封装该用户的用户名、密码、角色
        return new User(byUsername.getUsername(), byUsername.getPassword(), authorityList);
    }
}

